<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
    <link rel="stylesheet" href="/static/index.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>

<body>
    <!-- 悬浮搜索框 -->
    <div class="search-container">
        <div class="search-box">
            <input type="text" class="search-input" placeholder="搜索电影、电视剧、综艺..." id="searchInput">
            <button class="search-button" id="searchButton">
                <i class="fas fa-search"></i> 搜索
            </button>
        </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container">
        <div class="results-info">
            找到 <span class="results-count" id="resultsCount">8</span> 个结果
        </div>

        <div class="movies-list" id="moviesList">
            <!-- 电影卡片 -->
        </div>

        <script>
            // 搜索功能实现
            document.addEventListener('DOMContentLoaded', function () {
                const searchInput = document.getElementById('searchInput');
                const searchButton = document.getElementById('searchButton');
                const moviesList = document.getElementById('moviesList');
                const resultsCount = document.getElementById('resultsCount');
                const movieCards = document.querySelectorAll('.movie-card');

                // 创建电影卡片的辅助函数（根据实际API数据结构调整）
                function createMovieCard(movie) {
                    const card = document.createElement('div');
                    card.className = 'movie-card';

                    // 处理播放链接，如果有的话
                    let playButton = '';
                    if (movie.vod_play_url) {
                        playButton = `<button class="play-btn" onclick="playMovie('${movie.vod_id}')">播放</button>`;
                    }

                    // 处理演员和导演信息
                    let actorInfo = '';
                    if (movie.vod_actor) {
                        actorInfo = `<p class="actor">主演: ${movie.vod_actor}</p>`;
                    }

                    let directorInfo = '';
                    if (movie.vod_director) {
                        directorInfo = `<p class="director">导演: ${movie.vod_director}</p>`;
                    }

                    // 处理地区和时间
                    let areaInfo = '';
                    if (movie.vod_area) {
                        areaInfo = `<span class="area">${movie.vod_area}</span>`;
                    }

                    let yearInfo = '';
                    if (movie.vod_year) {
                        yearInfo = `<span class="year">${movie.vod_year}</span>`;
                    }

                    let remarksInfo = '';
                    if (movie.vod_remarks) {
                        remarksInfo = `<span class="remarks">${movie.vod_remarks}</span>`;
                    }

                    card.innerHTML = `
                        <div class="movie-poster">
                            <img src="${movie.vod_pic || '/static/default-poster.jpg'}"
                                 alt="${movie.vod_name || '未知电影'}"
                                 onerror="this.src='/static/default-poster.jpg'">
                            ${playButton}
                        </div>
                        <div class="movie-info">
                            <h3 class="movie-title">${movie.vod_name || '未知标题'}</h3>
                            ${movie.vod_sub ? `<p class="movie-subtitle">${movie.vod_sub}</p>` : ''}

                            <div class="movie-meta">
                                ${areaInfo}
                                ${yearInfo}
                                ${remarksInfo}
                            </div>

                            ${actorInfo}
                            ${directorInfo}

                            ${movie.type_name ? `<p class="type">类型: ${movie.type_name}</p>` : ''}
                        </div>
                    `;

                    // 添加点击事件
                    card.addEventListener('click', (e) => {
                        if (!e.target.closest('.play-btn')) {
                            showMovieDetail(movie);
                        }
                    });

                    return card;
                }

                // 显示电影详情
                function showMovieDetail(movie) {
                    console.log('显示详情:', movie);
                    // 这里实现显示详情的逻辑======================================================
                    postData(movie);
                }


                async function postData(dataToSend) {
                  try {
                    const response = await fetch('/video', {
                      method: 'POST',
                      headers: {
                        'Content-Type': 'application/json',
                      },
                      body: JSON.stringify(dataToSend)
                    });

                    // 检查响应是否成功
                    if (!response.ok) {
                      throw new Error(`网络响应异常: ${response.status}`);
                    }
                    // 解析响应JSON
                    const responseData = await response.json();
                    window.open(`/video`, '_blank');
                    console.log('操作成功:', responseData);
                    return responseData; // 你可以返回数据以便在其他地方使用
                  } catch (error) {
                    // 捕获网络错误或解析错误等
                    console.error('请求失败:', error);
                  }
                }
                // 更新搜索结果处理函数
                async function performSearch() {
                    const searchTerm = searchInput.value.trim();

                    if (searchTerm === '') {
                        // 如果搜索词为空，显示所有电影或清空结果
                        moviesList.innerHTML = '';
                        resultsCount.textContent = '0';
                        return;
                    }

                    try {
                        const response = await fetch('/', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ search_term: searchTerm })
                        });

                        if (!response.ok) {
                            throw new Error('搜索请求失败');
                        }

                        const searchResults = await response.json();

                        // 清空当前电影列表
                        moviesList.innerHTML = '';

                        if (searchResults.length === 0) {
                            moviesList.innerHTML = `
                                <div class="no-results">
                                    <i class="fas fa-search"></i>
                                    <p>没有找到与"${searchTerm}"相关的结果</p>
                                    <p>请尝试其他关键词</p>
                                </div>
                            `;
                            resultsCount.textContent = '0';
                        } else {
                            searchResults.forEach(movie => {
                                const movieCard = createMovieCard(movie);
                                moviesList.appendChild(movieCard);
                            });
                            resultsCount.textContent = searchResults.length;
                        }

                    } catch (error) {
                        console.error('搜索错误:', error);
                        moviesList.innerHTML = `
                            <div class="no-results">
                                <i class="fas fa-exclamation-triangle"></i>
                                <p>搜索过程中发生错误</p>
                                <p>请稍后重试</p>
                            </div>
                        `;
                    }
                }

                // 添加搜索表单提交事件监听（如果使用表单）
                const searchForm = document.getElementById('search-form');
                if (searchForm) {
                    searchForm.addEventListener('submit', function(e) {
                        e.preventDefault(); // 阻止表单默认提交
                        performSearch();
                    });
                }

                // 或者继续使用输入框的输入事件（可选）
                searchInput.addEventListener('input', debounce(performSearch, 300));

                // 防抖函数
                function debounce(func, wait) {
                    let timeout;
                    return function executedFunction(...args) {
                        const later = () => {
                            clearTimeout(timeout);
                            func(...args);
                        };
                        clearTimeout(timeout);
                        timeout = setTimeout(later, wait);
                    };
                }
                // 添加事件监听器
                searchButton.addEventListener('click', performSearch);

                searchInput.addEventListener('keypress', function (e) {
                    if (e.key === 'Enter') {
                        performSearch();
                    }
                });
            });
        </script>
</body>

</html>
